package org.apache.lenya.modules.xmldiff.usecases;

import org.apache.lenya.cms.publication.Document;
import org.apache.lenya.cms.repository.History;
import org.apache.lenya.cms.repository.Revision;
import org.apache.lenya.cms.site.usecases.SiteUsecase;
import org.apache.lenya.cms.workflow.WorkflowUtil;
import org.apache.lenya.workflow.Version;
import org.apache.lenya.workflow.Workflow;
import org.apache.lenya.workflow.Workflowable;

public class RevisionsDiffUsecase extends SiteUsecase {

	 /**
     * @see org.apache.lenya.cms.usecase.AbstractUsecase#initParameters() 
     *      
     */
    protected void initParameters() {
        super.initParameters();
        Document sourceDoc = getSourceDocument();
        if (sourceDoc != null) {
            try {
                History history = sourceDoc.getRepositoryNode().getHistory();

                int[] numbers = history.getRevisionNumbers();
                Revision[] revisions = new Revision[numbers.length];
                for (int i = 0; i < numbers.length; i++) {
                    revisions[i] = history.getRevision(numbers[i]);
                }
                setParameter("revisions", revisions);

                Boolean canRollback = Boolean.valueOf(WorkflowUtil.canInvoke(this.manager,
                        getDocumentFactory().getSession(), getLogger(), sourceDoc, getEvent()));
                setParameter("canRollback", canRollback);

                if (WorkflowUtil.hasWorkflow(this.manager, getSession(), getLogger(), sourceDoc)) {
                    Workflowable workflowable = WorkflowUtil.getWorkflowable(this.manager,
                            getSession(), getLogger(), sourceDoc);
                    Version latestVersion = workflowable.getLatestVersion();
                    String state;
                    if (latestVersion != null) {
                        state = latestVersion.getState();
                    } else {
                        Workflow workflow = WorkflowUtil.getWorkflowSchema(this.manager,
                                getSession(), getLogger(), sourceDoc);
                        state = workflow.getInitialState();
                    }
                    setParameter("workflowState", state);
                }
            } catch (final Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

	protected String getEvent() {
        return getParameterAsString("workflowEvent");        
    }
	
}
